const Component = (function () {

    let Component = function () {};
    let _this = Component.prototype;

    //=include ../../common/js/extends/Component.js

    /**
     * 顶部选择tab
     */
    _this.navbar = function (data = {}) {

        let _data = Object.assign({
            active: 'wait',
            onClick: function () {}
        }, data);

        let DOM = Render.create(`<div class="navbar">
            <ul class="navbar-box">
                <li class="navbar--item" data-id="wait"><span>待我审批</span></li>
                <li class="navbar--item" data-id="readed"><span>我已审批</span></li>
                <li class="navbar--item" data-id="copymy"><span>抄送我的</span></li>
            </ul>
        </div>`);

        Object.defineProperty(data, 'active', {
            get: function () {
                return _data.active;
            },
            set: function (val) {
                _data.active = val;
            }
        });

        // 选中默认
        $(DOM).find('.navbar--item[data-id="'+ _data.active +'"]').addClass('active');

        $(DOM).find('.navbar--item').on('click', function () {
            $(DOM).find('.navbar--item').removeClass('active');
            $(this).addClass('active');
            data.active = $(this).attr('data-id');
            _data.onClick(data.active);
        });

        data.el = DOM;

        return data;
    };

    /**
     * 工具框
     */
    _this.toolbar = function (data = {}) {
        let _data = Object.assign({
            // 是否可点全部已读（在列表全部为已读状态下的值是true，页面显示灰色）
            all_readed: true,
            // 是否打开搜索框
            isOpenSearch: false,
            openClickSearch: function () {},
            closeClickSearch: function () {},
            screenClick: function () {},
            readClick: function () {}
        }, data);

        let DOM = Render.create(`<div class="toolbar">
            <ul class="toolbar-box">
                <li class="toolbar--item search"><i class="fa fa-search"></i> 搜索</li>
                <li class="toolbar--item screen"><i class="fa fa-filter"></i> 筛选</li>
                <li class="toolbar--item set-read">全部已读</li>
            </ul>
        </div>`);

        let $Toolbar__item_search = $(DOM).find('.search');
        let $Toolbar__item_screen = $(DOM).find('.screen');
        let $Toolbar__item_set_read = $(DOM).find('.set-read');

        Object.defineProperty(data, 'openClickSearch', {
            enumerable: false,
            get: function () {
                return _data.openClickSearch;
            }
        });
        Object.defineProperty(data, 'closeClickSearch', {
            enumerable: false,
            get: function () {
                return _data.closeClickSearch;
            }
        });
        Object.defineProperty(data, 'isOpenSearch', {
            get: function () {
                return _data.isOpenSearch;
            },
            set: function (val) {
                _data.isOpenSearch = !!val;
                if (_data.isOpenSearch) {
                    $Toolbar__item_search.html('<i class="fa fa-search"></i> 取消搜索');
                    data.openClickSearch();
                } else {
                    $Toolbar__item_search.html('<i class="fa fa-search"></i> 搜索');
                    data.closeClickSearch();
                }
            }
        });

        let allReadedSetter = function (val) {
            if (val) {
                $Toolbar__item_set_read.hide();
                // $Toolbar__item_set_read.addClass('disabled');
            } else {
                $Toolbar__item_set_read.show();
                // $Toolbar__item_set_read.removeClass('disabled');
            }
        };

        Object.defineProperty(data, 'all_readed', {
            get: function () {
                return _data.all_readed;
            },
            set: function (val) {
                _data.all_readed = val;
                allReadedSetter(data.all_readed);
            }
        });
        allReadedSetter(data.all_readed);

        $Toolbar__item_search.on('click', function () {
            data.isOpenSearch = !data.isOpenSearch;
        });

        $Toolbar__item_screen.on('click', function () {
            data.screenClick();
        });

        $Toolbar__item_set_read.on('click', function () {
            if (!data.all_readed) {
                data.readClick();
            }
        });

        data.el = DOM;

        return data;
    };

    /**
     * 搜索框
     */
    _this.searchbar = function (data = {}) {
        let _data = Object.assign({
            // 是否在is_show=true打开时自动聚焦文本框
            auto_focus: false,
            is_show: false,
            search: '',
            onSubmit: function (val) {}
        }, data);

        let DOM = Render.create(`<div class="searchbar">
            <div class="searchbar-box">
                <div class="searchbar--write">
                    <input type="text" class="search--write-input" placeholder="搜索标题内容">
                </div>
                <div class="searchbar--btn">
                    <a href="javascript:;" class="search--btn-link">搜索</a>
                </div>
            </div>
        </div>`);

        // 设置显示隐藏
        _data.is_show ? $(DOM).addClass('on') : $(DOM).removeClass('on');
        Object.defineProperty(data, 'is_show', {
            get: function () {
                return _data.is_show
            },
            set: function (val) {
                _data.is_show = !!val;

                if (_data.is_show) {
                    $(DOM).addClass('on');
                    if (_data.auto_focus) {
                        setTimeout(() => {
                            $(DOM).find('.search--write-input').trigger('focus');
                        }, 200);
                    }
                } else {
                    $(DOM).removeClass('on');
                }
            }
        });

        // input输入监听
        let $Searchbar__write_input = $(DOM).find('.search--write-input');

        let $Search__btn_link = $(DOM).find('.search--btn-link');
        $Searchbar__write_input.val(_data.search)
        Object.defineProperty(data, 'search', {
            get: function () {
                return _data.search;
            },
            set: function (val) {
                _data.search = val;
                $Searchbar__write_input.val(_data.search);
                return val;
            }
        });
        $Searchbar__write_input.on('change', function () {
            data.search = this.value;
        });
        $Search__btn_link.on('click', function () {
            _data.onSubmit.call(_data);
        });

        data.el = DOM;

        return data;
    };

    /**
     * 列表
     */
    _this.list = function (data) {

        /**
         * 对返回数据统一过滤引擎方法
         */
        let request_filter = function (data, filter) {
            if (Util.type(filter) == 'function') {
                data = data.map(function(item) {
                    let data = filter.apply(this, arguments);
                    if (Util.type(data) == 'undefined' || Util.type(data) == 'null') {
                        return item;
                    }
                    return data;
                });
                // map后不是数组的项删除掉
                data = data.filter(item => {
                    return Util.type(item) == 'object';
                });
            }
            return data;
        };

        let st = null;

        let _data = Object.assign({
            list: [],
            api: '',
            page: 1,
            size: 10,
            query_id: '',
            title: '',
            is_read: '',
            model_id: '',
            status: '',
            onLoad: function (exec, type) {},
            // 下拉时出发重新渲染数据
            onRefresh: function (done) {
                if (data.api == '') {
                    return;
                }

                if (Util.type(_data.onLoad) != 'function') {
                    return;
                }

                data.page = 1;

                let request = {
                    page: data.page,
                    size: data.size,
                    title: data.title,
                    model_id: data.model_id,
                    is_read: data.is_read,
                    status: data.status,
                    query_id: data.query_id
                };

                _data.onLoad(function (filter) {
                    Api[data.api](request, function (result) {
                        result.data.data = request_filter(result.data.data, filter);
                        data.list.clear();
                        data.list.push(...result.data.data);
                        data.page += 1;
                        // 小于预定个数时，视为没有以后数据，noData=true
                        done(result.data.data.length < _data.size);
                    }, function (e) {
                        _this.toast(e.message).render();
                        done(true);
                    });
                }, 'refresh');
            },
            // 上拉时出发继续加载后续
            onContinue: function (done) {
                if (data.api == '') {
                    return;
                }

                if (Util.type(_data.onLoad) != 'function') {
                    return;
                }

                let request = {
                    page: data.page,
                    size: data.size,
                    title: data.title,
                    model_id: data.model_id,
                    is_read: data.is_read,
                    status: data.status,
                    query_id: data.query_id
                };

                _data.onLoad(function (filter) {
                    clearTimeout(st);
                    st = setTimeout(() => {
                        Api[data.api](request, function (result) {
                            result.data.data = request_filter(result.data.data, filter);
                            if (data.page == 1) {
                                data.list.clear();
                            }
                            data.list.push(...result.data.data);
                            data.page += 1;
                            // 小于预定个数时，视为没有以后数据，noData=true
                            done(result.data.data.length < data.size);
                        }, function (e) {
                            _this.toast(e.message).render();
                            done(true);
                        });
                    }, 800);
                }, 'continue');
            }
        }, data);

        /**
         * 统一注册
         */
        (function (names) {
            names.map(name => {
                Object.defineProperty(data, name, {
                    set: function (val) {
                        _data[name] = val;
                    },
                    get: function () {
                        return _data[name];
                    }
                });
            });
        })(['title','model_id','status','is_read','api','page','size','query_id']);

        data.list = [];
        data._cache_list_length = 0;

        let DOM = Render.create(`<div class="list"><ul class="list-box"></ul></div>`);

        let $List_box = $(DOM).find('.list-box');

        /**
         * 监听数组变化
         */
        data.list.__proto__ = getArrayArgumentations(method => {
            // push只向后追加
            let _list = [];
            if (method == 'push') {
                _list = data.list.slice(data._cache_list_length);
                _list.forEach(item => {
                    $List_box.append(this.listItem(item).el);
                });
            } else {
                $List_box.empty();
                data.list.forEach(item => {
                    $List_box.append(this.listItem(item).el);
                });
            }

            data._cache_list_length = data.list.length;
        });

        // 添加下拉上拉监听
        let Scroll = Util.scroll(DOM, {
            onRefresh: _data.onRefresh.bind(data),
            onContinue: _data.onContinue.bind(data)
        });

        data.refresh = function () {
            Scroll.refresh();
        };
        data.resetForm = function () {
            data.title = '';
            data.model_id = '';
            data.status = '';
            data.page = 1;
            data.query_id = '';
        };

        data.el = DOM;
        data.scroll = Scroll;
        return data;
    };

    /**
     * 列表item
     */
    _this.listItem = function (data) {
        let DOM = Render.create(`<li class="list--item">
            <div class="list--item-box">
                <a href="${Config.page('detail', {D_id: data.D_id,A_id: data.A_id,AD_id: data.AD_id})}" class="list--item-link" data-id="${data.id}">
                    <div class="list--item--title">
                        <span class="list--item--title-text">
                            <span>${data.title}</span>
                        </span>
                        <span class="list--item--title-time">${data.time}</span>
                    </div>
                    <div class="list--item--content">
                        <div class="list--item--content-avatar">
                            <img src="${data.avatar}" alt="" srcset="">
                        </div>
                        <div class="list--item--content-main">
                            <p class="list--item--content--title">
                                <span>${data.type}</span>
                            </p>
                        </div>
                    </div>
                </a>
            </div>
        </li>`);

        // 是否已读
        if (data.is_unreaded === true) {
            let BadgeDOM = Render.create(`<span class="badge badge-danger"></span>`);

            $(DOM).find('.list--item--title-text').append(BadgeDOM);

            $(DOM).find(".list--item-link").on("click", function () {
                if (BadgeDOM) {
                    BadgeDOM.parentNode.removeChild(BadgeDOM);
                    BadgeDOM = null;
                }
            });
        }


        // 详情
        let $list__item__content_main = $(DOM).find('.list--item--content-main');
        data.extra.forEach(extra => {
            $list__item__content_main.append(`<p>${extra}</p>`);
        });

        // 状态
        switch (data.status) {
            case 'approval':
                $(DOM).find('.list--item--content--title').append(`<span class="label label-info">审批中</span>`);
                break;
            case 'success':
                $(DOM).find('.list--item--content--title').append(`<span class="label label-success">已通过</span>`);
                break;
            case 'refuse':
                $(DOM).find('.list--item--content--title').append(`<span class="label label-danger">已拒绝</span>`);
                break;
            case 'cancel':
                $(DOM).find('.list--item--content--title').append(`<span class="label label-warning">已撤销</span>`);
                break;
            case 'stop':
                $(DOM).find('.list--item--content--title').append(`<span class="label label-dark">已终止</span>`);
                break;
            case 'invaldate':
                $(DOM).find('.list--item--content--title').append(`<span class="label label-gray">作废中</span>`);
                break;
            case 'invalidated':
                $(DOM).find('.list--item--content--title').append(`<span class="label label-gray">已作废</span>`);
                break;
        }

        return {
            el: DOM
        };
    };

    /**
     * 筛选dialog
     */
    let _CACHE_SCREEN_DIALOG_DOMS = null;
    _this.screenDialog = function (data = {}) {
        let _data = Object.assign({
            is_show: false,
            screen: [],
            onComplete: function () {}
        }, data);

        let DOM = Render.create(`<div class="half-screen-dialog">
            <div class="half-screen-dialog-box">
                <div class="half-screen-dialog--header"></div>
                <div class="half-screen-dialog--body"></div>
                <div class="half-screen-dialog--footer">
                    <button class="btn btn-primary screen-complete">确定</button>
                </div>
            </div>
        </div>`);

        let $Half_screen_dialog__body = $(DOM).find('.half-screen-dialog--body');

        // 加载数据
        data.screen.forEach(screen => {
            $Half_screen_dialog__body.append(this.screenDialogItem(screen).el);
        });

        // 切换显示隐藏
        Object.defineProperty(data, 'is_show', {
            get: function () {
                return _data.is_show;
            },
            set: function (val) {
                _data.is_show = !!val;

                if (_data.is_show) {
                    $('body').addClass('clamp');
                    $(DOM).addClass('on');
                    $(DOM).find('.half-screen-dialog-box').animate({
                        right: 0
                    });
                } else {
                    $('body').removeClass('clamp');
                    $(DOM).find('.half-screen-dialog-box').animate({
                        right: '-100%'
                    });
                    $(DOM).removeClass('on');
                    setTimeout(() => {
                        if (_CACHE_SCREEN_DIALOG_DOMS) {
                            _CACHE_SCREEN_DIALOG_DOMS.parentNode.removeChild(_CACHE_SCREEN_DIALOG_DOMS);
                            _CACHE_SCREEN_DIALOG_DOMS = null;
                        }
                    }, 600);
                }
            }
        });

        // 点击背景时
        $(DOM).on('click', function () {
            data.is_show = false;

            // 恢复上一次保存的值
            data.screen.forEach((item, index) => {
                item.value = _data.screen[index].value;
            });
        });

        // 禁止冒泡点击
        $(DOM).children().on('click', function (e) {
            e.stopPropagation();
        });

        // 点击确定
        $(DOM).find('.screen-complete').on('click', function () {
            // 关闭显示层
            data.is_show = false;

            // 收集数据
            let result = {};
            data.screen.map(screen => {
                result[screen.name] = screen.value;
            });

            // 发送数据通知
            _data.onComplete.call(data, result);
        });

        data.el = DOM;
        data.render = function (frame_selector) {
            // 清除上一次显示的DOM
            if (_CACHE_SCREEN_DIALOG_DOMS) {
                _CACHE_SCREEN_DIALOG_DOMS.parentNode.removeChild(_CACHE_SCREEN_DIALOG_DOMS);
            }

            _CACHE_SCREEN_DIALOG_DOMS = DOM;

            document.body.appendChild(DOM);
            setTimeout(() => {
                data.is_show = true;
            }, 0);
        }

        return data;
    };

    /**
     * 筛选dialog item
     */
    _this.screenDialogItem = function (data) {
        let _data = Object.assign({}, data);

        let DOM = Render.create(`<div class="half-screen-dialog--access">
            <div class="half-screen-dialog--access-box">
                <div class="half-screen-dialog--access--title ${data.color}">${data.title}</div>
                <ul class="half-screen-dialog--access--content"></ul>
            </div>
        </div>`);

        let $Half_screen_dialog__access__content = $(DOM).find('.half-screen-dialog--access--content');
        let _CACHE_LABEL_DOMS = [];

        data.options.forEach(item => {
            let LABEL_DOM = Render.create(`<li><button data-label="${item.value}" class="btn">${item.label}</button></li>`);

            // 点击修改value值
            let $Btn = $(LABEL_DOM).find('.btn');
            $Btn.on('click', function () {
                data.value = item.value;
            });

            // 将每个创建的li放入变量中待执行
            _CACHE_LABEL_DOMS.push(LABEL_DOM);
        });

        // 收集起来后统一渲染
        $Half_screen_dialog__access__content.append(_CACHE_LABEL_DOMS);

        // 设置setter执行效果
        let setter = function (val) {
            _CACHE_LABEL_DOMS.forEach(LABEL_DOM => {
                let $Btn = $(LABEL_DOM).find('.btn');
                if ($Btn.attr('data-label') == val) {
                    $Btn.addClass('btn-' + data.color);
                } else {
                    $Btn.removeClass('btn-' + data.color);
                }
            });
        }

        // 监听value值变化
        Object.defineProperty(data, 'value', {
            get: function () {
                return _data.value;
            },
            set: function (val) {
                _data.value = val;
                setter(val);
            }
        });

        // 初始进入时执行一遍setter
        setter(data.value);

        return {
            el: DOM
        };
    };

    return new Component;
})();